package classroom;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class Ratings extends InstituteListFragmentDAO {

	public static ListFragment newInstance(Context context) {
		Ratings lf = new Ratings();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.generic_list, null);

		new AsynchronousTask().execute();
		return root;
	}

	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ListAdapter listAdapter;

		String KEY_CAT = "k1";

		protected void onPreExecute() {
			super.onPreExecute();

		}

		protected String doInBackground(String... args) {

			try {
				ResultSet rs = DatabaseConnector.getStatement().executeQuery(
					"SELECT CONCAT(users.firstName,' ',users.lastname) as student FROM gradesheet"
					+ " INNER JOIN users on users.id = gradesheet.uid"
					+ " WHERE sid = (SELECT id FROM curriculum WHERE id = " + getSubjectID()
					+ " ) ORDER BY final DESC, midterm DESC, prelim DESC LIMIT 10");

				while (rs.next()) {

					m = new HashMap<String, String>();
					m.put(KEY_CAT, rs.getString("student"));
					arrayList.add(m);

				}

			} catch (SQLException e) {
				System.out.println("doInBackground: ** SQLException ** ");
				System.err.println(e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter =  new SimpleAdapter
					(getActivity(), arrayList,	R.layout.generic_detail, 
							new String[] {KEY_CAT}, new int[] { R.id.generic_text});

					setListAdapter(listAdapter);
				}
			});
		}
	} 

}